<template>
  <div class="ws-test-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>WebSocket 连接测试</span>
          <el-button type="primary" @click="testConnection">测试连接</el-button>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <h3>连接状态</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="连接状态">
              {{ connectionInfo.statusText }}
            </el-descriptions-item>
            <el-descriptions-item label="是否已连接">
              {{ connectionInfo.isConnected ? '是' : '否' }}
            </el-descriptions-item>
            <el-descriptions-item label="最后连接时间">
              {{ connectionInfo.lastConnectedTime || '未连接' }}
            </el-descriptions-item>
            <el-descriptions-item label="重连次数">
              {{ connectionInfo.reconnectCount }}
            </el-descriptions-item>
            <el-descriptions-item label="错误信息">
              {{ connectionInfo.connectionError || '无' }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="action-buttons">
            <el-button type="success" :disabled="connectionInfo.isConnected" @click="connect">
              连接
            </el-button>
            <el-button type="danger" :disabled="!connectionInfo.isConnected" @click="disconnect">
              断开
            </el-button>
            <el-button type="warning" @click="reconnect">重连</el-button>
          </div>
        </el-col>

        <el-col :span="12">
          <h3>消息统计</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="消息总数">
              {{ connectionInfo.messageCount }}
            </el-descriptions-item>
            <el-descriptions-item label="未读消息">
              {{ connectionInfo.unreadCount }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="action-buttons">
            <el-button type="info" @click="clearMessages">清空消息</el-button>
            <el-button type="primary" @click="markAllRead">全部已读</el-button>
          </div>
        </el-col>
      </el-row>

      <el-divider />

      <div class="test-message-buttons" style="margin-bottom: 16px">
        <el-button type="primary" @click="sendTestMessage('system')">发送系统消息</el-button>
        <el-button type="success" @click="sendTestMessage('comment')">发送评论消息</el-button>
        <el-button type="warning" @click="sendTestMessage('like')">发送点赞消息</el-button>
      </div>
      <h3>消息历史</h3>
      <div class="message-list">
        <el-card v-for="message in messageHistory" :key="message.id" class="message-item">
          <div class="message-header">
            <span class="message-type" :class="message.type">{{ message.type }}</span>
            <span class="message-time">{{ formatTime(message.createTime) }}</span>
            <span class="message-read" :class="{ unread: !message.isRead }">
              {{ message.isRead ? '已读' : '未读' }}
            </span>
          </div>
          <div class="message-content">
            <strong>{{ message.sender }}</strong>
            : {{ message.content }}
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useSocketStore } from '@/store/modules/socket';
import { sendNotificationByType } from '@/api/notification';
import { NOTIFICATION_DETAIL_TYPE } from '@/constants/common/notification-type';

const socketStore = useSocketStore();

const connectionInfo = computed(() => socketStore.getConnectionInfo());
const messageHistory = computed(() => socketStore.messageHistory);

const connect = () => {
  socketStore.connectWebSocket();
};

const disconnect = () => {
  socketStore.disconnectWebSocket();
};

const reconnect = () => {
  socketStore.manualReconnect();
};

const testConnection = () => {
  socketStore.testConnection();
};

const clearMessages = () => {
  socketStore.clearMessageHistory();
};

const markAllRead = () => {
  socketStore.markAllMessagesAsRead();
};

const formatTime = (time: string) => new Date(time).toLocaleString();

const sendTestMessage = async (type: 'system' | 'comment' | 'like') => {
  let content = '';
  let title = '';
  let userIds = [] as number[];
  let receiverId = '';
  let commenterName = '';
  let commentId = '';
  let targetId = '';
  let likerName = '';
  let targetType = '';
  let typeCode = NOTIFICATION_DETAIL_TYPE.DAILY_NEWS;
  switch (type) {
    case 'system':
      content = '这是一条系统通知';
      ((title = '系统通知'), (userIds = [2]));
      typeCode = NOTIFICATION_DETAIL_TYPE.ARTICLE_AUDIT_APPROVE;
      break;
    case 'comment':
      receiverId = '2';
      commenterName = '用户A';
      commentId = '12';
      typeCode = NOTIFICATION_DETAIL_TYPE.ARTICLE_COMMENT;
      break;
    case 'like':
      targetId = '1903356090214117376';
      receiverId = '2';
      likerName = '用户B';
      targetType = '文章';
      typeCode = NOTIFICATION_DETAIL_TYPE.ARTICLE_LIKE;
      break;
  }
  try {
    await sendNotificationByType(typeCode, {
      content,
      title,
      userIds,
      receiverId,
      commentId,
      commenterName,
      targetId,
      likerName,
      targetType
    });
  } catch (e) {
    // 可选：错误提示
    console.error('发送通知失败', e);
  }
};

onMounted(() => {
  // 自动连接
  if (!connectionInfo.value.isConnected) {
    connect();
  }
});
</script>

<style scoped>
.ws-test-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.message-list {
  max-height: 400px;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 10px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-type {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.message-type.system {
  background-color: #409eff;
}

.message-type.comment {
  background-color: #67c23a;
}

.message-type.like {
  background-color: #e6a23c;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-read {
  font-size: 12px;
  color: #67c23a;
}

.message-read.unread {
  color: #f56c6c;
}

.message-content {
  line-height: 1.5;
}
</style>
